<?php
/**
 * User Handler - Unified user operations
 */
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';
requireAdmin();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? $_POST['action'] ?? '';
    
    try {
        switch($action) {
            case 'update':
                $result = $pdo->prepare("
                    UPDATE users 
                    SET first_name = ?, last_name = ?, email = ?, phone = ?, role = ?, email_verified = ?
                    WHERE id = ?
                ");
                $result->execute([
                    $input['first_name'], $input['last_name'], $input['email'],
                    $input['phone'], $input['role'], $input['email_verified'] ?? 0,
                    $input['id']
                ]);
                echo json_encode(['success' => true, 'message' => 'User updated']);
                exit;
                
            case 'delete':
                $user_id = $input['id'];
                $user = getUserById($pdo, $user_id);
                if (!$user || $user['role'] === 'admin') {
                    echo json_encode(['success' => false, 'message' => 'Cannot delete admin']);
                    exit;
                }
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("DELETE FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE user_id = ?)");
                $stmt->execute([$user_id]);
                $stmt = $pdo->prepare("DELETE FROM orders WHERE user_id = ?");
                $stmt->execute([$user_id]);
                $stmt = $pdo->prepare("DELETE FROM cart_items WHERE user_id = ?");
                $stmt->execute([$user_id]);
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $pdo->commit();
                echo json_encode(['success' => true, 'message' => 'User deleted']);
                exit;
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

header('Location: users.php');

